package org.tgcloud.group.service.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.MapUtil;
import org.tgcloud.group.core.ResultMessage;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.entity.MjNormalUser;
import org.tgcloud.group.entity.MjOrder;
import org.tgcloud.group.entity.MjOtherProject;
import org.tgcloud.group.entity.SysLabelValue;
import org.tgcloud.group.repository.MjNormalUserMapper;
import org.tgcloud.group.repository.MjOtherProjectMapper;
import org.tgcloud.group.repository.SysLabelValueMapper;
import org.tgcloud.group.service.manager.SysManageService;
import org.tgcloud.group.web.controller.dto.otherProject.OtherProjectAppMsgDTO;
import org.tgcloud.group.web.controller.dto.otherProject.OtherProjectChannelMsgDTO;
import org.tgcloud.group.web.controller.dto.otherProject.OtherProjectChannelUserMsgDTO;
import org.tgcloud.group.web.controller.dto.user.UserDTO;
import org.tgcloud.group.web.controller.req.otherProject.*;
import org.tgcloud.group.web.controller.req.user.UserAppSearchReq;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: zhy
 * @Created: 2024-06-05-上午11:48
 * @Description:
 */
@Service
public class OtherProjectAppService {

    @Autowired
    private MjOtherProjectMapper otherProjectMapper;

    @Autowired
    private MjNormalUserMapper normalUserMapper;

    @Autowired
    private MjNormalUserMapper userMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private SysLabelValueMapper sysLabelValueMapper;

    @Autowired
    private SysManageService sysManageService;

    public APPResultMessage<Object, List> doAddAppOtherProject(int userId, OtherProjectReq req) {
        // 判断操作用户的用户类型，如果是助理，那么需要传开拓者id
        MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(userId);
        String addUserId = "";
        if (mjNormalUser != null && mjNormalUser.getUserType() == 2 && mjNormalUser.getIsAssistant() == 2){
            // 助理
            addUserId = req.getChoosePushUserId() + "," + userId;
        }else {
            addUserId = String.valueOf(userId);
        }
        MjOtherProject otherProject = new MjOtherProject();
        BeanUtils.copyProperties(req, otherProject);
        otherProject.setPushUserIds(addUserId);
        otherProject.setCreateTime(new Date());
        otherProject.setStatus((short) 2);
        otherProject.setCreateUserId(userId);
        otherProject.setCreateUserType(1);
        otherProject.setBiddingOneEndTime(new Date(req.getChooseEndTime()));
        otherProject.setIsDiscount(req.getIsDiscount());
        if (req.getIsDiscount() != null){
            if (req.getIsDiscount() == 1){
                otherProject.setDiscountPrice(req.getDiscountPrice());
                otherProject.setReferencePrice(otherProject.getTotalPrice().multiply(req.getDiscountPrice()).multiply(new BigDecimal(0.1)));
            }else {
                otherProject.setDiscountPrice(req.getDiscountPrice().divide(otherProject.getTotalPrice(), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(10)).setScale(2, BigDecimal.ROUND_HALF_UP));
                otherProject.setReferencePrice(req.getDiscountPrice());
            }
        }
        List<MjNormalUser> users = normalUserMapper.selectListByUserType((short) 2);
        JSONObject userStatusMap = new JSONObject();
        List idStringList = new ArrayList();
        for (MjNormalUser normalUser : users){
            userStatusMap.put("user_" + normalUser.getId().toString(), 86);
            idStringList.add(String.valueOf(normalUser.getId()));
        }
        String pushUserIds = String.join(",", idStringList);
        otherProject.setUserStatusMapJson(JSONObject.toJSONString(userStatusMap));
        otherProject.setBiddingPushUserIds(pushUserIds);
        otherProjectMapper.insertSelective(otherProject);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<OtherProjectAppMsgDTO, List> getOtherProjectMsg(int userId, OtherProjectIdReq req) {
        Short userType = 2;
        String userSearch = "$.user_" + userId;
        String userStatusSearch = userSearch;
        String userFirstPriceSearch = userSearch;
        String userSecondPriceSearch = userSearch;
        String userFirstRankNumSearch = userSearch;
        MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(userId);
        if (mjNormalUser != null && mjNormalUser.getUserType() == 1){
            // 渠道
            userType = 1;
            userStatusSearch = userStatusSearch + ".status";
            userFirstPriceSearch = userFirstPriceSearch + ".price";
            userSecondPriceSearch = userSecondPriceSearch + ".secondPrice";
            userFirstRankNumSearch = userFirstRankNumSearch + ".rankNum";
        }
        OtherProjectAppMsgDTO dto = otherProjectMapper.selectAppMsgById(req.getId(), userStatusSearch, userType,
                userFirstPriceSearch, userSecondPriceSearch, userFirstRankNumSearch);
        List<OtherProjectChannelMsgDTO> channelFirstPriceList = new ArrayList<>(); // 一次竞价的渠道用户价格
        List<OtherProjectChannelMsgDTO> channelSecondPriceList = new ArrayList<>(); // 二次竞价的渠道用户价格
        if (StringUtil.isNotBlank(dto.getChannelPriceMapJson())){
            JSONObject channelPriceMapJsonObject = JSONObject.parseObject(dto.getChannelPriceMapJson());
            if (mjNormalUser != null && mjNormalUser.getUserType() == 2){
                // 开拓者
                Map<Integer, String> pushUserMap = new TreeMap();
                if (mjNormalUser.getIsAssistant() == 2){
                    // 助理，获取对应的开拓者id
                    String[] split = mjNormalUser.getAssistantUserIds().split(",");
                    for (String sId : split){
                        pushUserMap.put(Integer.valueOf(sId), userMapper.selectByPrimaryKey(Integer.valueOf(sId)).getNickName());
                    }
                }else {
                    pushUserMap.put(userId, mjNormalUser.getNickName());
                }
                for (String userKey : channelPriceMapJsonObject.keySet()){
                    OtherProjectChannelUserMsgDTO msgDTO = channelPriceMapJsonObject.getObject(userKey, OtherProjectChannelUserMsgDTO.class);
                    if (pushUserMap.containsKey(msgDTO.getPushUserId())){
                        if (msgDTO.getPrice() != null && msgDTO.getPrice().compareTo(BigDecimal.ZERO) > 0){
                            OtherProjectChannelMsgDTO channelMsgDTO = new OtherProjectChannelMsgDTO();
                            BeanUtils.copyProperties(msgDTO, channelMsgDTO);
                            channelMsgDTO.setChannelName(userMapper.selectByPrimaryKey(msgDTO.getUserId()).getNickName());
                            channelMsgDTO.setPioneerName(pushUserMap.get(msgDTO.getPushUserId()));
                            channelFirstPriceList.add(channelMsgDTO);
                        }
                        if (msgDTO.getSecondPrice() != null && msgDTO.getSecondPrice().compareTo(BigDecimal.ZERO) > 0){
                            OtherProjectChannelMsgDTO channelMsgDTO = new OtherProjectChannelMsgDTO();
                            BeanUtils.copyProperties(msgDTO, channelMsgDTO);
                            channelMsgDTO.setChannelName(userMapper.selectByPrimaryKey(msgDTO.getUserId()).getNickName());
                            channelMsgDTO.setPioneerName(pushUserMap.get(msgDTO.getPushUserId()));
                            channelSecondPriceList.add(channelMsgDTO);
                        }
                    }
                }
            }
        }
        dto.setChannelFirstList(channelFirstPriceList);
        dto.setChannelSecondList(channelSecondPriceList);
        dto.setChannelPriceMapJson(null);
        String v4 = sysLabelValueMapper.selectValueBySysIdAndReadOne(4);
        String v5 = sysLabelValueMapper.selectValueBySysIdAndReadOne(5);
        dto.setBiddingPrice(new BigDecimal(v4));
        dto.setBiddingPoint(new BigDecimal(v5));
        // 判断开拓者底下的渠道是否中标
        if (dto.getLastUserId() != null){
            MjNormalUser channelUser = normalUserMapper.selectByPrimaryKey(dto.getLastUserId());
            if (userId == channelUser.getPushUserId()){
                dto.setIsLastPioneer(2);
            }
            if (mjNormalUser != null && mjNormalUser.getUserType() == 2){
                MjNormalUser pushUser = normalUserMapper.selectByPrimaryKey(channelUser.getPushUserId());
                // 开拓者
                dto.setLastPioneerName(pushUser.getNickName());
                dto.setLastChannelName(channelUser.getNickName());
                if (dto.getBiddingTwoTopPrice() != null) {
                    dto.setLastPrice(dto.getBiddingTwoTopPrice());
                } else if (dto.getBiddingOneFirstPrice() != null) {
                    dto.setLastPrice(dto.getBiddingOneFirstPrice());
                }
            }
        }
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(dto);
        successMessage.setResult(resultMessage);
        return successMessage;
    }


    public APPResultMessage<Object, List> doResetOtherProject(int userId, OtherProjectIdReq req) {
        otherProjectMapper.doResetAppOtherProject(req.getId());
        MjOtherProject otherProject = otherProjectMapper.selectByPrimaryKey(req.getId());
        JSONObject userStatusMap = new JSONObject();
        String[] split = otherProject.getPushUserIds().split(",");
        userStatusMap.put("user_" + split[0], 85);
        if (!split[0].equals(String.valueOf(otherProject.getCreateUserId()))){
            userStatusMap.put("user_" + otherProject.getCreateUserId(), 85);
        }
        otherProject.setUserStatusMapJson(JSONObject.toJSONString(userStatusMap));
        otherProjectMapper.updateByPrimaryKeySelective(otherProject);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        return successMessage;
    }

    public APPResultMessage<Object, List> doSetOtherProjectEndTime(int userId, OtherProjectBiddingEndTimeReq req) {
        MjOtherProject otherProject = otherProjectMapper.selectByPrimaryKey(req.getId());
        if (otherProject.getStatus() == 1){
            otherProject.setStatus((short) 2);
            String pushUserIds = otherProject.getPushUserIds();
            String[] split = pushUserIds.split(",");
            String userStatusSearch = "$.user_" + split[0];
            otherProjectMapper.updateUserStatusById(req.getId(), userStatusSearch, (short) 86);
        }
        otherProject.setBiddingOneEndTime(new Date(req.getEndTime()));
        otherProject.setIsDiscount(req.getIsDiscount());
        if (req.getIsDiscount() != null){
            if (req.getIsDiscount() == 1){
                otherProject.setDiscountPrice(req.getDiscountPrice());
                otherProject.setReferencePrice(otherProject.getTotalPrice().multiply(req.getDiscountPrice()).multiply(new BigDecimal(0.1)));
            }else {
                otherProject.setDiscountPrice(req.getDiscountPrice().divide(otherProject.getTotalPrice(), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(10)).setScale(2, BigDecimal.ROUND_HALF_UP));
                otherProject.setReferencePrice(req.getDiscountPrice());
            }
        }
        List<MjNormalUser> users = normalUserMapper.selectListByUserType((short) 2);
        List<Integer> idList = users.stream().map(MjNormalUser::getId).collect(Collectors.toList());
        String ids = StringUtils.join(idList, ",");
        otherProject.setBiddingPushUserIds(ids);
        JSONObject userStatusMap = new JSONObject();
        if (StringUtil.isBlank(otherProject.getUserStatusMapJson())){
            for (MjNormalUser normalUser : users){
                userStatusMap.put("user_" + normalUser.getId().toString(), 86);
            }
            otherProject.setUserStatusMapJson(JSONObject.toJSONString(userStatusMap));
        }else {
            JSONObject jsonObject = JSONObject.parseObject(otherProject.getUserStatusMapJson());
            for (MjNormalUser normalUser : users){
                String key = "user_" + normalUser.getId().toString();
                Integer value = 86;
                if (jsonObject.containsKey(key)){
                    Integer integer = jsonObject.getInteger(key);
                    if (integer == 85){
                        value = 86;
                    }else {
                        value = integer;
                    }
                }
                userStatusMap.put(key, value);
            }
            otherProject.setUserStatusMapJson(JSONObject.toJSONString(userStatusMap));
        }
        otherProjectMapper.updateByPrimaryKeySelective(otherProject);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        return successMessage;
    }

    public APPResultMessage<Object, List> doSureOtherProjectPushChannelUser(int userId, OtherProjectChannelUserIdReq req) {
        MjOtherProject otherProject = otherProjectMapper.selectByPrimaryKey(req.getId());
        String[] split = req.getUserIds().split(",");
        List<MjNormalUser> mjNormalUsers = userMapper.selectUserListByIds(split);
        if (StringUtil.isBlank(otherProject.getChannelPriceMapJson())){
            // 如果数据库中该字段没有存储过数据，是null，那么进行这一步操作
            JSONObject userStatusMap = new JSONObject();
            for (MjNormalUser user : mjNormalUsers){
                String key = "user_" + user.getId();
                OtherProjectChannelUserMsgDTO channelUserMsgDTO = new OtherProjectChannelUserMsgDTO();
                channelUserMsgDTO.setUserId(user.getId());
                channelUserMsgDTO.setStatus(74);
                channelUserMsgDTO.setPushUserId(user.getPushUserId());
                userStatusMap.put(key, channelUserMsgDTO);
            }
            otherProject.setChannelPriceMapJson(JSONObject.toJSONString(userStatusMap));
            otherProjectMapper.updateByPrimaryKeySelective(otherProject);
        }else {
            JSONObject channelPriceMapJsonObject = JSONObject.parseObject(otherProject.getChannelPriceMapJson());
            for (MjNormalUser user : mjNormalUsers){
                String userKey = "user_" + user.getId();
                String key = "$." + userKey;
                OtherProjectChannelUserMsgDTO channelUserMsgDTO = new OtherProjectChannelUserMsgDTO();
                if (!channelPriceMapJsonObject.containsKey(userKey)){
                    channelUserMsgDTO.setUserId(user.getId());
                    channelUserMsgDTO.setStatus(74);
                    channelUserMsgDTO.setPushUserId(user.getPushUserId());
                    otherProjectMapper.updateChannelById(req.getId(), key, MapUtil.objectToMap(channelUserMsgDTO));
                }
            }
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, UserDTO> getOtherProjectUserAppList(int userId, UserAppSearchReq req) {
        MjOtherProject otherProject = otherProjectMapper.selectByPrimaryKey(req.getOtherProjectId());
        String pushUserIdStr = null;
        if (StringUtil.isNotBlank(otherProject.getChannelPriceMapJson())){
            List<String> ids = new ArrayList<>();
            JSONObject channelPriceMapJson = JSONObject.parseObject(otherProject.getChannelPriceMapJson());
            for (String key : channelPriceMapJson.keySet()){
                String uId = key.replace("user_", "");
                ids.add(uId);
            }
            String[] array = ids.toArray(new String[0]);
            pushUserIdStr = String.join(",", array);
        }

        String[] split = null;
        List<String> pushUserList = new ArrayList<>();
        if (StringUtil.isNotBlank(pushUserIdStr)){
            String[] split1 = pushUserIdStr.split(",");
            pushUserList = new ArrayList<>(Arrays.asList(split1));
            split = pushUserList.toArray(new String[0]);
        }
        if (StringUtil.isNotBlank(req.getNotInUserIds())) {
            List<String> newPushUserList = Arrays.asList(req.getNotInUserIds().split(","));
            pushUserList.addAll(newPushUserList);
            split = pushUserList.toArray(new String[0]);
        }

        String[] pushUsers = null;
        if (StringUtil.isNotBlank(req.getPushUserIds())){
            pushUsers = req.getPushUserIds().split(",");
        }
        MjNormalUser user = userMapper.selectByPrimaryKey(userId);
        if (user.getIsAssistant() == 2 && req.getUserType() == 1){
            String biddingPushUserIds = otherProject.getBiddingPushUserIds();
            if (StringUtil.isNotBlank(biddingPushUserIds)){
                pushUsers = biddingPushUserIds.split(",");
            }
            //如果是助理，只可以看见所属开拓者的渠道
            List<String> a = new ArrayList();
            for (String pushUser : pushUsers) {
                MjNormalUser mjNormalUser = userMapper.selectByPrimaryKey(userId);
                String assistantUserIds = mjNormalUser.getAssistantUserIds();
                for (String s : assistantUserIds.split(",")) {
                    if (pushUser.equals(s)){
                        a.add(s);
                    }
                }
            }
            pushUsers = a.toArray(new String[0]);
        }

        if (req.getPageNum() != null && req.getPageSize() != null){
            PageHelper.startPage(req.getPageNum(),req.getPageSize());
            List<UserDTO> users = userMapper.selectAppListByKeyword(req.getUserType(),split,pushUsers);
            PageInfo<UserDTO> tables = new PageInfo<>(users);
            ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage<Object, UserDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            List<UserDTO> users = userMapper.selectAppListByKeyword(req.getUserType(),split,pushUsers);
            ResultMessage resultMessage = ResultMessage.builder().setList(users);
            APPResultMessage<Object, UserDTO> successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }

    public APPResultMessage<Object, List> doPushOtherProjectChannelPrice(int userId, OtherProjectChannelPriceReq req) {
        if (req.getIsDiscount() == 1 && req.getDiscountPrice() != null && req.getDiscountPrice().compareTo(new BigDecimal(10)) > -1){
            return new APPResultMessage<>(6001, "折扣不能大于10，请重新填写");
        }
        MjOtherProject otherProject = otherProjectMapper.selectByPrimaryKey(req.getId());
        Integer type = otherProject.getStatus() < 3 ? 1 : 2; // 1、一次竞价，2、二次竞价
        APPResultMessage appResultMessage = orderService.doCheckReferencePrice(userId, otherProject.getReferencePrice());
        if (appResultMessage.getKey() != 1000){
            return appResultMessage;
        }
        BigDecimal totalPrice = otherProject.getTotalPrice();
        if (req.getIsDiscount() != null){
            if (req.getIsDiscount() == 1){
                totalPrice = otherProject.getTotalPrice().multiply(req.getDiscountPrice()).multiply(new BigDecimal(0.1));
            }else {
                totalPrice = req.getDiscountPrice();
            }
        }
        String channelPriceMapJson = otherProject.getChannelPriceMapJson();
        String userKey = "user_" + userId;
        if (StringUtil.isNotBlank(channelPriceMapJson)){
            JSONObject channelPriceMapJsonObject = JSONObject.parseObject(channelPriceMapJson);
            if (channelPriceMapJsonObject.containsKey(userKey)){
                String userSearch = "$." + userKey;
                OtherProjectChannelUserMsgDTO dto = channelPriceMapJsonObject.getObject(userKey, OtherProjectChannelUserMsgDTO.class);
                if (type == 2){
                    if (dto.getPrice() == null || dto.getPrice().compareTo(BigDecimal.ZERO) < 1){
                        return new APPResultMessage<>(6001, "一次竞价未提交价格，不允许进入二次竞价");
                    }
                    dto.setStatus(76);
                    dto.setIsSecondDiscount(req.getIsDiscount());
                    dto.setSecondPrice(totalPrice.setScale(4, BigDecimal.ROUND_HALF_UP));
                    dto.setSecondTime(new Date().getTime());
                    dto.setSecondCommitRecord(2);
                }else {
                    dto.setIsDiscount(req.getIsDiscount());
                    dto.setPrice(totalPrice.setScale(4, BigDecimal.ROUND_HALF_UP));
                    dto.setFirstTime(new Date().getTime());
                    dto.setAbandonRecord(1);
                    dto.setFirstCommitRecord(2);
                }
                otherProjectMapper.updateChannelById(req.getId(), userSearch, MapUtil.objectToMap(dto));
            }
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, List> doStartOtherProjectTwoBidding(int userId, OtherProjectIdReq req) {
        MjOtherProject otherProject = otherProjectMapper.selectByPrimaryKey(req.getId());
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
        if (null != normalUser && normalUser.getUserLevel() != null){
            SysLabelValue sysLabelValue = sysLabelValueMapper.selectByPrimaryKey(normalUser.getUserLevel());
            String desc = sysLabelValue.getDesc();
            if (StringUtil.isNotBlank(desc)){
                if (otherProject.getReferencePrice().compareTo(new BigDecimal(desc)) > 0){
                    return new APPResultMessage<>(6001, "您当前的等级不支持进行下一步操作，请升级后再处理");
                }
            }
        }
        if (otherProject.getBiddingStartTwo() == null || otherProject.getBiddingStartTwo() == 1){
            String v19 = sysManageService.doReadOneSysLabelValue(19);
            otherProjectMapper.updateStartTwoBidding(req.getId(), userId, v19);
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, List> doJoinOtherProjectTwoBidding(int userId, OtherProjectIdReq req) {
        MjOtherProject otherProject = otherProjectMapper.selectByPrimaryKey(req.getId());
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
        if (null != normalUser && normalUser.getUserLevel() != null){
            SysLabelValue sysLabelValue = sysLabelValueMapper.selectByPrimaryKey(normalUser.getUserLevel());
            String desc = sysLabelValue.getDesc();
            if (StringUtil.isNotBlank(desc)){
                if (otherProject.getReferencePrice().compareTo(new BigDecimal(desc)) > 0){
                    return new APPResultMessage<>(6001, "您当前的等级不支持进行下一步操作，请升级后再处理");
                }
            }
        }
        String userIds = String.valueOf(userId);
        if(StringUtil.isNotBlank(otherProject.getBiddingStartTwoUserIds())){
            userIds = otherProject.getBiddingStartTwoUserIds() + "," + userIds;
        }
        otherProject.setBiddingStartTwoUserIds(userIds);
        otherProjectMapper.updateByPrimaryKeySelective(otherProject);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, List> doRefuseOtherProjectChannelOrder(int userId, Short userType, OtherProjectIdReq req) {
        MjOtherProject otherProject = otherProjectMapper.selectByPrimaryKey(req.getId());
        if (userType == 2){
            MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(otherProject.getLastUserId());
            Integer pushUserId = mjNormalUser.getPushUserId();
            MjNormalUser user2 = normalUserMapper.selectByPrimaryKey(userId);
            if (user2.getIsAssistant() == 1) {
                if (userId != pushUserId){
                    return APPResultMessage.getErrorMessage("该开拓者暂无放弃订单的权限");
                }
            }else {
                if (user2.getAssistantUserIds().indexOf(pushUserId.toString()) == -1){
                    return APPResultMessage.getErrorMessage("该助理暂无放弃订单的权限");
                }
            }
            userId = otherProject.getLastUserId();
        }
        JSONObject channelPriceMapJsonObject = JSONObject.parseObject(otherProject.getChannelPriceMapJson());
        String userKey = "user_" + userId;
        String userAbandonKey = "user_" + userId + ".abandonRecord";
        String key = "$." + userKey + ".status";
        String searchUserAbandonKey = "$." + userAbandonKey;
        if (channelPriceMapJsonObject.containsKey(userKey)){
            String refuseChannelIds = otherProject.getChannelRefuseIds();
            if (StringUtil.isBlank(refuseChannelIds)){
                otherProject.setChannelRefuseIds(String.valueOf(userId));
            }else {
                refuseChannelIds = refuseChannelIds + "," + userId;
                otherProject.setChannelRefuseIds(refuseChannelIds);
            }
            otherProjectMapper.updateByPrimaryKeySelective(otherProject);
            OtherProjectChannelUserMsgDTO dto = channelPriceMapJsonObject.getObject(userKey, OtherProjectChannelUserMsgDTO.class);
            if (dto.getAbandonRecord() == null || dto.getAbandonRecord() == 1){
                Integer hasJoinUserNum = 0;
                List<OtherProjectChannelUserMsgDTO> dtoList = new ArrayList();
                for (String uKey : channelPriceMapJsonObject.keySet()){
                    OtherProjectChannelUserMsgDTO msgDTO = channelPriceMapJsonObject.getObject(uKey, OtherProjectChannelUserMsgDTO.class);
                    if (msgDTO.getAbandonRecord() == 1 && msgDTO.getUserId() != userId && msgDTO.getFirstCommitRecord() == 2){
                        hasJoinUserNum = hasJoinUserNum + 1;
                        dtoList.add(msgDTO);
                    }
                }
                if (otherProject.getLastUserId() != null && otherProject.getLastUserId() == userId){
                    Integer newLastUserId = null;
                    // 说明还有其他参与的渠道商，为0表示只有当前这个准备拒绝的渠道商
                    if (hasJoinUserNum > 0){
                        // 最终确认的渠道商修改
                        // 判断二次竞价，如果没有进行二次竞价，那么就判断一次竞价
                        if (otherProject.getBiddingStartTwo() == 2){
                            // 使用Stream API进行排序
                            List<OtherProjectChannelUserMsgDTO> sortedTransactions = dtoList.stream()
                                    // 先按Price降序
                                    .sorted(Comparator.comparing(OtherProjectChannelUserMsgDTO::getSecondPrice, Comparator.reverseOrder())
                                            // 然后在Price相同的情况下按FirstTime升序
                                            .thenComparing(OtherProjectChannelUserMsgDTO::getSecondTime))
                                    .collect(Collectors.toList());
                            OtherProjectChannelUserMsgDTO dto1 = sortedTransactions.get(0);
                            newLastUserId = dto1.getUserId();
                            updateLastUserIdById(req.getId(), dto1.getUserId(), dto1.getSecondPrice());
                        }else {
                            // 使用Stream API进行排序
                            List<OtherProjectChannelUserMsgDTO> sortedTransactions = dtoList.stream()
                                    // 先按Price降序
                                    .sorted(Comparator.comparing(OtherProjectChannelUserMsgDTO::getPrice, Comparator.reverseOrder())
                                            // 然后在Price相同的情况下按FirstTime升序
                                            .thenComparing(OtherProjectChannelUserMsgDTO::getFirstTime))
                                    .collect(Collectors.toList());
                            OtherProjectChannelUserMsgDTO dto1 = sortedTransactions.get(0);
                            newLastUserId = dto1.getUserId();
                            updateLastUserIdById(req.getId(), dto1.getUserId(), dto1.getPrice());
                        }
                    }else {
                        otherProjectMapper.updateStatusById(req.getId(), (short) 5);
                        updateLastUserIdById(req.getId(), null, null);
                        // 把所有的开拓者状态设置为88
                        String[] split = otherProject.getBiddingPushUserIds().split(",");
                        for (String s : split){
                            otherProjectMapper.updateUserStatusById(req.getId(), "$.user_" + s, (short) 88);
                        }
                    }
                    // 修改最终确认的渠道商对应的开拓者
                    if (newLastUserId != null){
                        MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(newLastUserId);
                        Integer pushUserId = mjNormalUser.getPushUserId();
                        JSONObject jsonObject = JSONObject.parseObject(otherProject.getUserStatusMapJson());
                        for (String key1 : jsonObject.keySet()){
                            String pushUserKey = "user_" + pushUserId;
                            if (key1.equals(pushUserKey)){
                                String userStatusSearch = "$.user_" + pushUserId;
                                otherProjectMapper.updateUserStatusById(req.getId(), userStatusSearch, (short) 99);
                            }else {
                                if (jsonObject.getInteger(key1) == 99){
                                    String userStatusSearch = "$.user_" + pushUserId;
                                    otherProjectMapper.updateUserStatusById(req.getId(), userStatusSearch, (short) 88);
                                }
                            }
                        }
                        // 修改渠道的状态
                        String channelUserKey = "$.user_" + newLastUserId + ".status";
                        otherProjectMapper.updateChannelStatusById(req.getId(), channelUserKey, 93);
                    }
                }
                otherProjectMapper.updateChannelStatusById(req.getId(), key, 94);
                otherProjectMapper.updateChannelStatusById(req.getId(), searchUserAbandonKey, 2);
            }
        }
        return APPResultMessage.getSuccessMessage();
    }

    public void updateLastUserIdById(Integer id, Integer userId, BigDecimal price){
        MjOtherProject otherProject = otherProjectMapper.selectByPrimaryKey(id);
        if (otherProject.getBiddingStartTwo() == null || otherProject.getBiddingStartTwo() == 1){
            otherProjectMapper.updateFirstLastUserIdById(id, userId, price);
        }else {
            otherProjectMapper.updateSecondLastUserIdById(id, userId, price);
        }
    }

}
